#!/usr/bin/env python
# encoding: utf-8

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

import os, time, random
from collections import OrderedDict
import json

import serial
import serial.tools.list_ports

from common.libs.Log import logging

from ui.writeConfDialog import Ui_Dialog

CONFIG_PATH = os.getcwd()+'/conf/write.json'

class writeConfDialog(QDialog, Ui_Dialog):

    signal_send = pyqtSignal(str, str, str)
    axis_max = 0

    def __init__(self, parent=None, config=None, config_path=None):
        super(writeConfDialog, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle('设置窗口')
        # self.setWindowState(Qt.WindowMaximized)
        # self.setMinimumHeight(300)
        # self.setMinimumWidth(450)

        # 读取配置信息
        self.readConfig()

        self.pushButton_save.clicked.connect(self.writeConfig)
        self.pushButton_write.clicked.connect(self.startWrite)

        # 字体
        self.font = QFont()
        self.font.setFamily("Agency FB")
        self.font.setPointSize(28)
        font = self.font

        # 尺寸
        self.size = QSize(100, 100)
        size = self.size

        self.pushButton_write.setFont(font)
        # self.pushButton_write.setMinimumSize(size)
        self.pushButton_save.setFont(font)
        # self.pushButton_write.setMinimumSize(size)

        # ui加载
        self.uiLoad()

        # 写入标志
        self.write_flag = False
        self.write_cnt = 0
        self.write_step = ""
        self.write_timer = QTimer()
        self.write_timer.timeout.connect(self.writeTimer)

        # 读取信息提示框
        self.writeInfoMessageBox = QMessageBox()  # Message Box that doesn't run
        self.writeInfoMessageBox.setIcon(QMessageBox.Warning)
        self.writeInfoMessageBox.setText("信息写入中\r\n请稍后...")
        self.writeInfoMessageBox.setWindowFlags(Qt.FramelessWindowHint)
        self.writeInfoMessageBox.setWindowTitle("提示")
        self.writeInfoMessageBox.setFont(self.font)
        self.writeInfoMessageBox.setStandardButtons(QMessageBox.Ok)
        self.writeInfoMessageBox.button(QMessageBox.Ok).hide()

    def uiLoad(self):
        self.lineEdit_speed_dict = {}
        self.lineEdit_direction_dict = {}
        self.lineEdit_pulse_dict = {}
        self.lineEdit_distance_dict = {}
        self.lineEdit_precision_dict = {}
        size = self.size
        font = self.font
        axis = self.config['axis']
        self.axis_max = len(axis) 

        label_speed = QLabel("速度")
        label_speed.setFont(font)
        label_direction = QLabel("方向")
        label_direction.setFont(font)
        label_pulse = QLabel("脉冲")
        label_pulse.setFont(font)
        label_distance = QLabel("距离")
        label_distance.setFont(font)
        label_precision = QLabel("精度")
        label_precision.setFont(font)
        self.gridLayout.addWidget(label_direction, 0, 1, 1, 1)
        self.gridLayout.addWidget(label_speed, 0, 2, 1, 1)
        self.gridLayout.addWidget(label_pulse, 0, 3, 1, 1)
        self.gridLayout.addWidget(label_distance, 0, 4, 1, 1)
        self.gridLayout.addWidget(label_precision, 0, 5, 1, 1)

        i = 1
        for k in axis:
            # 获取信息
            item = axis[k]

            speed = item['speed'] if 'speed' in item else ''
            direction = item['direction'] if 'direction' in item else ''
            pulse = item['pulse'] if 'pulse' in item else ''
            distance = item['distance'] if 'distance' in item else ''
            precision = item['precision'] if 'precision' in item else ''

            # 创建控件
            label_name = QLabel("%s轴"%k)
            label_name.setFont(font)

            lineEdit_speed = QLineEdit(speed)
            # lineEdit_speed.textChanged.connect(self.textChangedName)
            lineEdit_speed.setMinimumSize(size)
            lineEdit_speed.setFont(font)

            lineEdit_direction = QLineEdit(direction)
            lineEdit_direction.setMinimumSize(size)
            lineEdit_direction.setFont(font)

            lineEdit_pulse = QLineEdit(pulse)
            lineEdit_pulse.setMinimumSize(size)
            lineEdit_pulse.setFont(font)

            lineEdit_distance = QLineEdit(distance)
            lineEdit_distance.setMinimumSize(size)
            lineEdit_distance.setFont(font)

            lineEdit_precision= QLineEdit(precision)
            lineEdit_precision.setMinimumSize(size)
            lineEdit_precision.setFont(font)

            # 添加控件
            self.gridLayout.addWidget(label_name, i, 0, 1, 1)
            self.gridLayout.addWidget(lineEdit_direction, i, 1, 1, 1)
            self.gridLayout.addWidget(lineEdit_speed, i, 2, 1, 1)
            self.gridLayout.addWidget(lineEdit_pulse, i, 3, 1, 1)
            self.gridLayout.addWidget(lineEdit_distance, i, 4, 1, 1)
            self.gridLayout.addWidget(lineEdit_precision, i, 5, 1, 1)

            # 保存控件
            self.lineEdit_speed_dict[k] = lineEdit_speed
            self.lineEdit_direction_dict[k] = lineEdit_direction
            self.lineEdit_pulse_dict[k] = lineEdit_pulse
            self.lineEdit_distance_dict[k] = lineEdit_distance
            self.lineEdit_precision_dict[k] = lineEdit_precision
            i += 1

    def accept(self):
        if self.writeConfig():
            QDialog.accept(self)

    # def reject(self):
    #     QDialog.reject(self)

    def writeConfig(self):
        """写入配置文件"""
        try:
            # 保存坐标信息
            axis = self.config['axis']
            for k in axis:
                axis[k]['speed'] = str(self.lineEdit_speed_dict[k].text())
                axis[k]['direction'] = str(self.lineEdit_direction_dict[k].text())
                axis[k]['pulse'] = str(self.lineEdit_pulse_dict[k].text())
                axis[k]['distance'] = str(self.lineEdit_distance_dict[k].text())
                axis[k]['precision'] = str(self.lineEdit_precision_dict[k].text())
            self.config['axis'] = axis

            save = json.dumps(self.config, indent=4)
            with open(CONFIG_PATH, 'w', encoding='utf-8') as f:
                f.write(save)
            QMessageBox.information(self,"提示","保存成功", QMessageBox.Yes)
            return True
        except Exception as e:
            logging.info(e)
            QMessageBox.information(self,"提示","保存失败, 文件被调用", QMessageBox.Yes)
            return False


    def readConfig(self):
        """读取配置文件"""
        with open(CONFIG_PATH, 'r', encoding='utf-8') as f:
            self.config = json.loads(f.read(), object_pairs_hook=OrderedDict)

    def startWrite(self):
        self.write_flag = True
        self.write_step = 0
        self.write_timer.start(500)
        self.writeInfoMessageBox.exec()

    def writeTimer(self):
        if self.write_flag:
            if self.write_step < self.axis_max:
                axis = chr(0x61+self.write_step)
                data = "%s%s.%s,%s%s.%s"%(
                    self.lineEdit_direction_dict[axis].text(),
                    self.lineEdit_speed_dict[axis].text(),
                    self.lineEdit_pulse_dict[axis].text(),
                    self.lineEdit_direction_dict[axis].text(),
                    self.lineEdit_precision_dict[axis].text(),
                    self.lineEdit_distance_dict[axis].text(),
                )
                self.signal_send.emit(axis, '!', data)
                self.write_step += 1
            else:
                self.writeInfoMessageBox.accept()
                QMessageBox.information(
                    self, '提示', '写入下位机完成，请测试写入结果！', QMessageBox.Yes)
                self.write_flag = False
                self.write_timer.stop()

    def dealRecv(self, recv):
        pass
            
    # def textChangedName(self, txt): 
    #     obj = self.sender() # 获取发射信号的对象
    #     for k in self.lineEdit_name_dict:
    #         if self.lineEdit_name_dict[k] == obj:
    #             self.signal_name_changed.emit(k, txt)
    #             break

    # def textChangedPos(self, txt): 
    #     obj = self.sender() # 获取发射信号的对象
    #     for k in self.lineEdit_pos_dict:
    #         if self.lineEdit_pos_dict[k] == obj:
    #             self.signal_pos_changed.emit(k, txt)
    #             break

    # def stateChangedEnable(self, state): 
    #     obj = self.sender() # 获取发射信号的对象
    #     for k in self.checkBox_enable_dict:
    #         if self.checkBox_enable_dict[k] == obj:
    #             self.signal_enable_changed.emit(k, state)
    #             break

